from flask import Blueprint, request, redirect, url_for
from common.libs.Helper import ops_renderJSON, iPagenation, ops_render
from common.models.person import Person

from common.models.pickclass import Pickclass
from application import db, app
from common.libs.DataHelper import getCurrentTime
from common.models.record import Record
import flask_excel as excel
import os
from sqlalchemy import and_, or_

person_page = Blueprint("person_page", __name__)


def pagesadmin(pagedata, pagecontroller, pagefunction):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': pagedata.count(),
        "page_size": 10,
        'page': page,
        'url': "/" + pagecontroller + "/" + pagefunction + "?",
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    data = pagedata[offset:limit]

    return pages, data


def pagessearch(parterindex, url):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': parterindex.count(),
        "page_size": 10,
        'page': page,
        'url': "/person/personsearch?" + url,
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    parterindex = parterindex[offset:limit]

    return pages, parterindex


@person_page.route('/personindex', methods=['GET', 'POST'])
def personindex():
    personindex = Person.query.limit(10)
    pages, personindex = pagesadmin(pagedata=personindex, pagecontroller="person", pagefunction="personindex")
    num = str(Person.query.limit(10).count())
    return ops_render("/person/personindex.html", {"personindex": personindex, "pages": pages, "num": num})


# @person_page.route('/personsearch', methods=['GET', 'POST'])
# def personsearch():
#     a = request.args.to_dict()
#     for key in list(a.keys()):
#         if a.get(key) == "不限":
#             del a[key]
#     for key in list(a.keys()):
#         if not a.get(key):
#             del a[key]
#     if "p" in a:
#         del a["p"]
#
#     company = request.args.get('company')
#     department = request.args.get('department')
#     hrclass = request.args.get('hrclass')
#     sap = request.args.get('sap')
#     url = "company" + company + "&department=" + department + "&hrclass=" + hrclass + "&sap=" + sap
#
#     personindex = Person.query.filter_by(**a)
#     pages, Personindex = pagessearch(personindex, url)
#
#     return ops_render("/person/personindex.html", {"personindex": personindex, "pages": pages})
#
#
# # 搜索函数
# def make_excel_list(data, column_names):
#     list_data = []
#     list_data.append(column_names)
#     for item in data:
#         tmp = [item.htsn, item.name, item.project, item.aname, item.bname, item.filename, item.filenum, item.num,
#                item.dfnum, item.cwnum, item.cdnum, item.creater.nickname, item.creater.company, item.creater.department]
#         list_data.append(tmp)
#     return list_data


@person_page.route('/personsearch', methods=['GET', 'POST'])
def personsearch():
    # 字典接收所有参数

    company = request.args.get('company')
    department = request.args.get('department')
    hrclass = request.args.get('hrclass')
    sap = request.args.get('sap')

    # 多选数组准备
    list1 = []
    list2 = []
    list3 = []
    if company != "null":
        companylist = company.split(',')
        for i in companylist:
            list1.append("%" + i + "%")
        print(list1)
    if department != "null":
        departmentlist = department.split(',')
        for i in departmentlist:
            list2.append("%" + i + "%")
        print(list2)
    if hrclass != "null":
        hrclasslist = hrclass.split(',')
        for i in hrclasslist:
            list3.append("%" + i + "%")
        print(list3)




    # 获取参数拼接翻页url

    url = "company=" + company + "&department=" + department + "&hrclass=" + hrclass + "&sap=" + sap

    if sap != "":
        personindex = Person.query.filter_by(sap=sap)
        pages, personindex = pagessearch(personindex, url)
        return ops_render("/person/personindex.html",
                          {"personindex": personindex, "pages": pages, "num": 1})


    else:
        personindex = Person.query.filter(or_(*[Person.company.like(w) for w in list1])).filter(
            or_(*[Person.department.like(w) for w in list2])).filter(
            or_(*[Person.hrclass.like(w) for w in list3])).order_by(
            Person.sap.desc())
        pages, personindex = pagessearch(personindex, url)
        num = str(Person.query.filter(or_(*[Person.company.like(w) for w in list1])).filter(
            or_(*[Person.department.like(w) for w in list2])).filter(
            or_(*[Person.hrclass.like(w) for w in list3])).order_by(
            Person.sap.desc()).count())
        return ops_render("/person/personindex.html",
                          {"personindex": personindex, "pages": pages, "num": num})


